/**
 * 性能监控和首屏渲染优化插件
 * 监控Core Web Vitals指标，自动优化首屏加载
 */

import { App, ref, onMounted } from 'vue'

// Core Web Vitals类型定义
interface PerformanceMetrics {
  // 首次内容绘制 (FCP)
  fcp?: number
  // 最大内容绘制 (LCP)
  lcp?: number
  // 首次输入延迟 (FID)
  fid?: number
  // 累积布局偏移 (CLS)
  cls?: number
  // 首次字节 (TTFB)
  ttfb?: number
}

export default {
  install(app: App) {
    // 1. 监控Performance API
    if (typeof window !== 'undefined') {
      // 监控页面加载性能
      monitorPageLoad()

      // 监控路由切换性能
      setupRouterPerformanceMonitoring()

      // 监控首屏渲染时间
      monitorFirstPaint()

      // 监控LCP（最大内容绘制）
      monitorLCP()

      // 监控CLS（累积布局偏移）
      monitorCLS()

      // 预加载关键资源
      preloadCriticalResources()
    }

    // 2. 添加全局性能配置
    app.config.performance = true

    // 3. 暴露性能指标API
    app.config.globalProperties.$getPerformanceMetrics = () => {
      return getPerformanceMetrics()
    }
  },
}

/**
 * 监控页面加载性能
 */
function monitorPageLoad() {
  window.addEventListener('load', () => {
    setTimeout(() => {
      const navigation = performance.getEntriesByType('navigation')[0] as any

      const metrics = {
        // DNS查找时间
        dnsTime: navigation.domainLookupEnd - navigation.domainLookupStart,
        // TCP连接时间
        tcpTime: navigation.connectEnd - navigation.connectStart,
        // 请求响应时间
        requestTime: navigation.responseEnd - navigation.requestStart,
        // DOM解析时间
        domParseTime: navigation.domContentLoadedEventEnd - navigation.responseEnd,
        // 资源加载时间
        loadTime: navigation.loadEventEnd - navigation.navigationStart,
        // 首字节时间
        ttfb: navigation.responseStart - navigation.navigationStart,
      }

      console.log('📊 页面加载性能指标:', metrics)

      // 发送性能数据到监控服务（如果需要）
      reportPerformanceMetrics('page_load', metrics)
    }, 0)
  })
}

/**
 * 监控首次绘制和首次内容绘制
 */
function monitorFirstPaint() {
  const paintEntries = performance.getEntriesByType('paint') as PerformanceEntry[]

  paintEntries.forEach(entry => {
    console.log(`🎨 ${entry.name}: ${entry.startTime}ms`)
  })
}

/**
 * 监控LCP (Largest Contentful Paint)
 */
function monitorLCP() {
  if (!('PerformanceObserver' in window)) return

  const observer = new PerformanceObserver(list => {
    const entries = list.getEntries()
    const lastEntry = entries[entries.length - 1] as any

    console.log(`🚀 LCP (最大内容绘制): ${lastEntry.startTime.toFixed(2)}ms`)

    // LCP超过2.5秒需要优化
    if (lastEntry.startTime > 2500) {
      console.warn('⚠️  LCP超过2.5秒，需要优化！')
    }

    reportPerformanceMetrics('lcp', { value: lastEntry.startTime })
  })

  observer.observe({ type: 'largest-contentful-paint', buffered: true })
}

/**
 * 监控CLS (Cumulative Layout Shift)
 */
function monitorCLS() {
  if (!('PerformanceObserver' in window)) return

  let clsValue = 0
  const observer = new PerformanceObserver(list => {
    for (const entry of list.getEntries() as any) {
      if (!entry.hadRecentInput) {
        clsValue += entry.value
      }
    }

    console.log(`📐 CLS (累积布局偏移): ${clsValue.toFixed(4)}`)

    // CLS超过0.1需要优化
    if (clsValue > 0.1) {
      console.warn('⚠️  CLS超过0.1，需要优化！')
    }

    reportPerformanceMetrics('cls', { value: clsValue })
  })

  observer.observe({ type: 'layout-shift', buffered: true })
}

/**
 * 预加载关键资源
 */
function preloadCriticalResources() {
  // 暂时禁用字体预加载（避免控制台警告）

  // 预加载首屏关键API
  const criticalAPIs = ['/api/user/info', '/api/menu', '/api/dashboard/stats']

  criticalAPIs.forEach(api => {
    const link = document.createElement('link')
    link.rel = 'prefetch'
    link.href = api
    document.head.appendChild(link)
  })

  // DNS预解析
  const dnsPrefetch = document.createElement('link')
  dnsPrefetch.rel = 'dns-prefetch'
  dnsPrefetch.href = '//api.example.com'
  document.head.appendChild(dnsPrefetch)
}

/**
 * 监控路由切换性能
 */
function setupRouterPerformanceMonitoring() {
  // 如果使用Vue Router
  const router = (window as any).$router
  if (router) {
    router.beforeEach((to: any, from: any, next: any) => {
      // 记录导航开始时间
      performance.mark('route-navigation-start')
      next()
    })

    router.afterEach(() => {
      // 记录导航结束时间
      setTimeout(() => {
        performance.mark('route-navigation-end')
        performance.measure('route-navigation', 'route-navigation-start', 'route-navigation-end')

        const measure = performance.getEntriesByName('route-navigation')[0]
        console.log(`🔄 路由切换时间: ${measure.duration.toFixed(2)}ms`)
      }, 0)
    })
  }
}

/**
 * 获取所有性能指标
 */
function getPerformanceMetrics(): PerformanceMetrics {
  const navigation = performance.getEntriesByType('navigation')[0] as any
  const paintEntries = performance.getEntriesByType('paint')

  const metrics: PerformanceMetrics = {
    ttfb: navigation.responseStart - navigation.navigationStart,
    fcp: paintEntries.find(entry => entry.name === 'first-contentful-paint')?.startTime,
    lcp: 0, // 需要单独监控
    cls: 0, // 需要单独监控
    fid: 0, // 需要单独监控
  }

  return metrics
}

/**
 * 发送性能指标到监控服务
 */
function reportPerformanceMetrics(type: string, data: any) {
  // 这里可以集成第三方性能监控服务
  // 例如：Google Analytics、New Relic、Sentry等

  // 示例：发送到自定义监控API
  if (navigator.sendBeacon) {
    navigator.sendBeacon('/api/performance', JSON.stringify({ type, data, timestamp: Date.now() }))
  } else {
    fetch('/api/performance', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ type, data, timestamp: Date.now() }),
      keepalive: true,
    }).catch(() => {}) // 静默失败
  }
}

/**
 * 性能优化建议器
 */
export class PerformanceAdvisor {
  private metrics: PerformanceMetrics = {}

  analyze(): string[] {
    const suggestions: string[] = []

    // 分析TTFB
    if (this.metrics.ttfb && this.metrics.ttfb > 600) {
      suggestions.push('TTFB过高，建议优化服务器响应速度或使用CDN')
    }

    // 分析FCP
    if (this.metrics.fcp && this.metrics.fcp > 1800) {
      suggestions.push('FCP过高，建议减少首屏资源大小或使用预加载')
    }

    // 分析LCP
    if (this.metrics.lcp && this.metrics.lcp > 2500) {
      suggestions.push('LCP过高，建议优化关键资源加载或使用HTTP/2')
    }

    // 分析CLS
    if (this.metrics.cls && this.metrics.cls > 0.1) {
      suggestions.push('CLS过高，建议为所有媒体元素指定尺寸')
    }

    return suggestions
  }
}

/**
 * 创建性能优化组件
 */
export const PerformanceMonitor = {
  name: 'PerformanceMonitor',
  template: `
    <div v-if="debug" class="performance-monitor">
      <div class="metrics">
        <div v-for="(value, key) in metrics" :key="key" class="metric">
          <span class="label">{{ key.toUpperCase() }}:</span>
          <span class="value">{{ value }}ms</span>
        </div>
      </div>
    </div>
  `,
  props: {
    debug: {
      type: Boolean,
      default: false,
    },
  },
  setup(props: any) {
    const metrics = ref<PerformanceMetrics>({})

    onMounted(() => {
      metrics.value = getPerformanceMetrics()
    })

    return {
      metrics,
    }
  },
}
